package middleware

import (
	"api/internal/types"
	"fmt"
	jwt "github.com/golangblogs/gojwt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"strconv"
)

type AuthUserMiddleware struct {
}

func NewAuthUserMiddleware() *AuthUserMiddleware {
	return &AuthUserMiddleware{}
}

func (m *AuthUserMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		fmt.Println("触发了中间件")

		token := r.Header.Get("token")
		if token == "" {
			resp := types.Response{
				Message: "token is nil",
				Code:    1001,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}

		newJwt := jwt.NewJWT("Token")
		claims, err := newJwt.ParseToken(token)
		if err != nil {
			resp := types.Response{
				Message: "token is invalid",
				Code:    1001,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}

		fmt.Println(claims.ID)
		userId := claims.ID
		r.ParseForm()

		r.Form.Set("userId", strconv.Itoa(int(userId)))
		// Passthrough to next handler if need
		next(w, r)
	}
}
